﻿using DotNetCommon.Data;
using DotNetCommon.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNetCommon.Validate
{
    /// <summary>
    /// 模型校验帮助类
    /// </summary>
    public static class ValidateModelHelper
    {
        /// <summary>
        /// 使用给定的校验逻辑校验对象,提取出校验失败提示
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dto"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static string ValidErrorMessage<T>(T dto, Action<ValidateContext<T>> func)
        {
            var ctx = new ValidateContext<T>(dto, "");
            try
            {
                func(ctx);
            }
            catch (ValidateException) { }

            //组装结果(含子节点)
            var msg = FetchMessage(ctx);
            return msg;
        }

        /// <summary>
        /// 使用给定的校验逻辑校验对象,返回结果响应对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dto"></param>
        /// <param name="func"></param>
        /// <param name="errorCode"></param>
        /// <returns></returns>
        public static Result ValidResult<T>(T dto, Action<ValidateContext<T>> func, int errorCode = 0)
        {
            var msg = ValidErrorMessage(dto, func);
            if (msg.IsNullOrEmptyOrWhiteSpace()) return Result.Ok();
            return Result.NotOk(msg, errorCode, null, null);
        }

        /// <summary>
        /// 使用给定的校验逻辑校验对象,返回结果响应对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dto"></param>
        /// <param name="func"></param>
        /// <param name="errorCode"></param>
        /// <returns></returns>
        public static void ValidThrow<T>(T dto, Action<ValidateContext<T>> func, int errorCode = 0)
        {
            var msg = ValidErrorMessage(dto, func);
            if (msg.IsNullOrEmptyOrWhiteSpace()) return;
            ResultException.Throw(msg, errorCode);
        }

        internal static string FetchMessage(ValidateContext ctx)
        {
            var msg = "";
            if (ctx.ErrorMessage.Count > 0)
            {
                foreach (var item in ctx.ErrorMessage)
                {
                    msg += item.error + "\r\n";
                }
            }
            if (ctx.Children.Count > 0)
            {
                foreach (var item in ctx.Children)
                {
                    var _t = FetchMessage(item);
                    msg += _t;
                }
            }
            return msg;
        }
    }
}
